import java.util.ArrayList;
import java.util.List;

public class num39 {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        int temp = 0;
        dfs(candidates,target,temp,res,path);
        return res;
    }

    private void dfs(int[] candidates, int target, int temp, List<List<Integer>> res, List<Integer> path) {
        if(temp == target) {
            res.add(new ArrayList<>(path));
            return;
        }else if(temp > target)  {
            return;
        }
        for (int i = 0; i < candidates.length; i++) {
            if(path.isEmpty()) {
                path.add(candidates[i]);
                temp += candidates[i];
                dfs(candidates,target,temp,res,path);
                temp -= candidates[i];
                path.remove(path.size() - 1);
            }else if(candidates[i] >= path.get(path.size() - 1)) {
                temp += candidates[i];
                path.add(candidates[i]);
                dfs(candidates,target,temp,res,path);
                temp -= candidates[i];
                path.remove(path.size() - 1);
            }
        }
    }
}
